import * as antdHelper from "./antd-helper";

const fileTypes = {
  video: [
    "avi",
    "wmv",
    "mpeg",
    "mp4",
    "m4v",
    "mov",
    "asf",
    "flv",
    "f4v",
    "rmvb",
    "rm",
    "3gp",
  ],
  music: [
    "mp3",
    "wav",
    "wma",
    "mp2",
    "flac",
    "midi",
    "ra",
    "ape",
    "aac",
    "cda",
    "mov",
  ],
  image: ["jpeg", "jpg", "png", "gif", "bmp", "tiff", "webp", "heif"],
  app: ["rar", "zip", "7z", "xz", "gz"],
};

export function getFileType(fileName) {
  let tmp = fileName.toLocaleLowerCase().split(".");
  let type = tmp[tmp.length - 1];
  type = type.replace(".", "");
  for (let k in fileTypes) {
    let arr = fileTypes[k];
    if (arr.includes(type)) {
      return k;
    }
  }
  return "unknow";
}
export function downloadFile(url, name, ext) {
	let fileName = name;
	if (ext) {
		fileName += "." + ext;
	}
	let type = getFileType(fileName);
	if (type == "image") {
		return downloadImage(url, name, ext);
	} else {
		var downloadLink = document.createElement("a");
		downloadLink.href = url;
		downloadLink.download = fileName;
		document.body.appendChild(downloadLink);
		downloadLink.click();
		document.body.removeChild(downloadLink);
	}
}
export function downloadImage(imgsrc, name, type) {
  if (!type) {
		type = "png";
	}
  antdHelper.loading("downloading...");
  let image = new Image();
  image.setAttribute("crossOrigin", "anonymous");
  image.onload = function () {
    let canvas = document.createElement("canvas");
    canvas.width = image.width;
    canvas.height = image.height;
    let context = canvas.getContext("2d");
    context?.drawImage(image, 0, 0, image.width, image.height);
    let url = canvas.toDataURL(`image/${type}`);
    let a = document.createElement("a");
    let event = new MouseEvent("click");
    a.download = name + "." + type;
    a.href = url;
    a.dispatchEvent(event);
    antdHelper.loading();
  };
  image.src = imgsrc;
}
